# pip install -i https://pypi.tuna.tsinghua.edu.cn/simple selenium pandas openpyxl xlrd

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.events import EventFiringWebDriver, AbstractEventListener
import time
import pandas as pd



class NavigationListener(AbstractEventListener):
    def after_navigate_to(self, url, driver):
        print(f"Navigated to: {url}")

def inputCategory(driver,category):
    driver.find_element(by=By.CSS_SELECTOR,value="input[placeholder=\"输入关键词，“回车键(Enter)”确定\"]").clear()
    driver.find_element(by=By.CSS_SELECTOR,value="input[placeholder=\"输入关键词，“回车键(Enter)”确定\"]").send_keys(category)
    driver.find_element(by=By.CSS_SELECTOR,value="#chooseCate .btn-warning").click()
    time.sleep(0.1)
    try:
        driver.find_element(by=By.CSS_SELECTOR,value=".j_tree_box .check-item").click()
        time.sleep(1.5)
        driver.find_element(by=By.CSS_SELECTOR,value="#chooseCate > div.p-s.border-top.clearfix > span > button.btn.btn-success.m-lr-l").click()
    except Exception as e:
        print(category,": 分类错误")


def get(driver,url,expireAt=5):
    driver.get(url)
    driver.implicitly_wait(expireAt)

def navTouserLogin(driver,username,password):
    get(driver,"https://passport.shop.jd.com/login/index.action/jdm?ReturnUrl=https%3A%2F%2Fshop.jd.com%2Fjdm%2Fhome")
    driver.find_element(by=By.ID,value="loginname").send_keys(username)
    driver.find_element(by=By.CSS_SELECTOR,value="input[type=\"password\"]").send_keys(password)
    driver.find_element(by=By.CLASS_NAME,value="password__submit").click()
    time.sleep(8)

def navToXongdao(driver):
    get(driver,"https://fw.jd.com/main/myService/MyService/MyServicePortal/Home")
    driver.find_element(by=By.CSS_SELECTOR,value=".el-table__row .el-table_1_column_4 button").click()
    driver.implicitly_wait(2)
    time.sleep(1)
    driver.switch_to.window(driver.window_handles[0])
     
     
     
def categoryMoving(driver,spus,category):
    # 打开商品迁移页面
    get(driver,"https://jdcopy.huoyuan88.cn/se/batch/category/category_move.jsp?modifyType=CATEGORY_MOVE")
    driver.implicitly_wait(10)
    
    # 切换到按商品编号
    driver.find_element(by=By.LINK_TEXT,value="按商品编号搜索").click()
    time.sleep(0.1)
    
    
    # 输入修改的商品编号
    driver.find_element(by=By.TAG_NAME,value="textarea").send_keys(spus)
    time.sleep(0.1)
    
    
    # 打开选择分类界面
    driver.find_element(by=By.CSS_SELECTOR,value="#category_move > form > div > div").click()
    time.sleep(1)
    
    # 输入分类并搜索
    inputCategory(driver,category)
    time.sleep(0.1)
    
    # 预览效果
    driver.find_element(by=By.CSS_SELECTOR,value="#j-page-bottom button.btn.btn-warning.btn-lg.j_modify_preview.m-r-xl").click()
    time.sleep(0.1)
    
    # 提交
    driver.find_element(by=By.CSS_SELECTOR,value="#j-page-bottom button.btn.btn-primary.btn-lg.j_modify_submit").click()
    time.sleep(0.1)
    
    # 二次确认
    driver.find_element(by=By.CSS_SELECTOR,value="button.btn.btn-primary.m-r-m.j_confirm_sure_btn").click()
    
    
def getResult(driver):
    driver.find_element(by=By.CSS_SELECTOR,value="div.modal.fade.in.j_modal_confirm  button.btn.btn-primary.m-r-m.j_confirm_sure_btn").click()
    driver.implicitly_wait(10)
    while(True):
        try:
            time.sleep(2)
            status_list = driver.find_element(by=By.XPATH,value="//*[@id=\"histroy-list\"]//tr/td[4]/span")
            print(status_list.text)
            if(status_list.text == "已完成"):
                break
            driver.find_element(by=By.CSS_SELECTOR,value="#histroy-list button.j_refresh_btn").click()
        except:
            continue
        
     
def exportExcel(read_file,export_file):
    old_data = pd.read_excel(read_file,usecols=["商品ID","商品名称","商品货号","商品分类"],index_col="商品ID")
    group_data = old_data.groupby(by=["商品分类"]).groups
    excel_data = []
    for k,v in group_data.items():
        spus = []
        for spu in v.to_list():
            spus.append(str(spu)+"\n")
        excel_data.append([k,k.split("->")[-1]," ".join(spus)])
    new_data = pd.DataFrame(excel_data,columns=["原类别","新类别","商品编号"])
    new_data.to_excel(f"{export_file}.xlsx",index=False)

class NavigationListener(AbstractEventListener):
    def after_navigate_to(self, url, driver):
        print(f"Navigated to: {url}")


def setup(username, password,excel):
    driver = EventFiringWebDriver(webdriver.Chrome(), NavigationListener())
    navTouserLogin(driver,username=username,password=password)
    navToXongdao(driver)
    if not excel:
        return
    data = pd.read_excel(f"{excel}.xlsx",index_col="原类别")
    process_data = []
    success_data = []
    error_data = []

    for k,v in data.iterrows():
        export = None
        try:
            export = [k,v["新类别"],v["商品编号"]]
            print(k,v["新类别"],v["商品编号"])
            categoryMoving(driver,v["商品编号"],v["新类别"])
            success_data.append(export)
            getResult(driver)
        except:
            error_data.append(export)
        finally:
            process_data.append(export)
        time.sleep(0.5)

    pd.DataFrame(success_data,columns=["原类别","新类别","商品编号"]).to_excel(f"{excel}_success.xlsx",index=False)
    pd.DataFrame(error_data,columns=["原类别","新类别","商品编号"]).to_excel(f"{excel}_fail.xlsx",index=False)
    driver.quit()



# exportExcel("本店商品导出SPU_2024_08_29_南北.xls","南北")
setup("xse磊耀南北干货rft","pkv2j0i!","南北")
